//依赖收集
let id = 0;

//基于发布订阅的思想
class Dep {
  constructor() {
    //每次实例化会有唯一的id
    this.id = id++;

    //收集订阅者(监听器)
    this.subs = [];
  }

  //订阅
  addSub(watcher) {
    this.subs.push(watcher);
  }

  //把watcher存入dep中，然后把dep也存入watcher中 多对多
  depend() {
    if (Dep.target) {
      // console.log(Dep.target) => watcher;
      //执行某一项watcher里面的addDep方法
      //添加Dep依赖
      Dep.target.addDep(this);
    }
  }

  //发布
  notify() {
    this.subs.forEach(watcher => {
      watcher.update();
    });
  }
}

//存放当前watcher的栈
let stack = [];

//vue里还会导出两个函数
//保存当前的watcher是哪一个
export function pushTarget(watcher) {
  Dep.target = watcher;
  stack.push(watcher);
}

//删除栈里当前的watcher
export function popTarget() {
  // 出栈
  stack.pop();
  //指向前一个watcher
  Dep.target = stack[stack.length - 1];
}

export default Dep;